﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using LetiLib.Data;

namespace LedCenter.GUI.PopupControls
{
#if DEBUG
    public partial class PlaylistPopupControl : MiddlePopupControl
#else 
    public partial class PlaylistPopupControl : PopupControl
#endif
    {
        public PlaylistPopupControl()
        {
            InitializeComponent();
            ImageList imageList = new ImageList();
            imageList.ImageSize = new Size(64, 64);
            imageList.ColorDepth = ColorDepth.Depth24Bit;
            this.thumbnailListView.LargeImageList = imageList;
            this.thumbnailListView.View = View.LargeIcon;
        }

        public PlaylistPopupControl(PLAYLIST_POPUP p, bool editMode = false)
            : base((POPUP)p, editMode)
        {
            InitializeComponent();
            
            //gcPlaylist.Enabled = true;
            //imageDetails1.Enabled = false;

            ImageList imageList = new ImageList();
            imageList.ImageSize = new Size(64, 64);
            imageList.ColorDepth = ColorDepth.Depth24Bit;
            this.thumbnailListView.LargeImageList = imageList;
            this.thumbnailListView.View = View.LargeIcon;


            //imageDetails1.Visible = true;
            populateGallery();
            imageDetails1.btnOK.Click +=new EventHandler(imgDetailBtnUpdate_Click);
        }

        private void populateGallery()
        {
            ImageList imageList = this.thumbnailListView.LargeImageList;

            // Remove image in icon list
            this.thumbnailListView.LargeImageList.Images.Clear();
            // Remove items in list
            this.thumbnailListView.Items.Clear();

            int index = 0;

            if (((PLAYLIST_POPUP)_popup).Images != null && ((PLAYLIST_POPUP)_popup).Images.Count > 0)
            {
                string basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                foreach (IMAGE img in ((PLAYLIST_POPUP)_popup).Images)
                {
                    string path = basePath + "\\DB\\Images\\" + img.ImageCode + ".png";
                    Image sourceBitmap;
                    if (System.IO.File.Exists(path))
                    {
                        sourceBitmap = Image.FromFile(path);
                    }
                    else
                    {
                        sourceBitmap = new Bitmap(120, 120);
                        Graphics g = Graphics.FromImage(sourceBitmap);
                        g.Clear(Color.Red);
                    }

                    AddImage(sourceBitmap, img.PlayOrder.ToString());
                    index++;
                }

            }
            this.Height = this.MaximumSize.Height;
        }

        ImageDetails imageDetails1 = new ImageDetails();
        #region | Thumbnails |

        private bool AddImage(Image image,string caption)
        {
            if (image == null)
            {
                return false;
            }

            // Insert image to imagelist
            this.thumbnailListView.LargeImageList.Images.Add(image);

            // Add new item with caption
            this.thumbnailListView.Items.Add(caption);
            // Update new item's image index
            this.thumbnailListView.Items[this.thumbnailListView.Items.Count - 1].ImageIndex = 
                this.thumbnailListView.Items.Count-1;
            return true;
        }

        private bool RemoveImage(int index)
        {
            if (index < 0 || index >= this.thumbnailListView.LargeImageList.Images.Count)
                return false;

            // Remove image in icon list
            this.thumbnailListView.LargeImageList.Images.RemoveAt(index);
            // Remove items in list
            this.thumbnailListView.Items.RemoveAt(index);

            return true;
        }

        private Image getThumbnaiImage(int width, Image img)
        {
            Image thumb = new Bitmap(width, width);
            Image tmp = null;

            if (img.Width < width && img.Height < width)
            {
                using (Graphics g = Graphics.FromImage(thumb))
                {
                    int xoffset = (int)((width - img.Width) / 2);
                    int yoffset = (int)((width - img.Height) / 2);
                    g.DrawImage(img, xoffset, yoffset, img.Width, img.Height);
                }
            }
            else
            {
                Image.GetThumbnailImageAbort myCallback = new
                    Image.GetThumbnailImageAbort(ThumbnailCallback);

                if (img.Width == img.Height)
                {
                    thumb = img.GetThumbnailImage(
                             width, width,
                             myCallback, IntPtr.Zero);
                }
                else
                {
                    int k = 0;
                    int xoffset = 0;
                    int yoffset = 0;

                    if (img.Width < img.Height)
                    {
                        k = (int)(width * img.Width / img.Height);
                        tmp = img.GetThumbnailImage(k, width, myCallback, IntPtr.Zero);
                        xoffset = (int)((width - k) / 2);

                    }

                    if (img.Width > img.Height)
                    {
                        k = (int)(width * img.Height / img.Width);
                        tmp = img.GetThumbnailImage(width, k, myCallback, IntPtr.Zero);
                        yoffset = (int)((width - k) / 2);
                    }

                    using (Graphics g = Graphics.FromImage(thumb))
                    {
                        g.DrawImage(tmp, xoffset, yoffset, tmp.Width, tmp.Height);
                    }
                }
            }

            /*
            using (Graphics g = Graphics.FromImage(thumb))
            {
                g.DrawRectangle(Pens.Green, 0, 0, thumb.Width - 1, thumb.Height - 1);
            }
            */
            return thumb;
        }

        public bool ThumbnailCallback()
        {
            return true;
        }

        public List<Image> images = new List<Image>();
        int selectedImageIndex = -1;
        private void thumbnailListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            //return;
            if (thumbnailListView.SelectedIndices.Count != 1) return;
            if (thumbnailListView.SelectedIndices[0] < 0 ||
                thumbnailListView.SelectedIndices[0] >= thumbnailListView.Items.Count) return;

            selectedImageIndex = thumbnailListView.SelectedIndices[0];
            
        }

        private void thumbnailListView_ItemActivate(object sender, EventArgs e)
        {
            if (selectedImageIndex < 0 ||
                selectedImageIndex >= thumbnailListView.Items.Count) return;

            imageDetails1.DataSource = ((PLAYLIST_POPUP)_popup).Images[selectedImageIndex];

            ShowImageDetails(imageDetails1);
        }

        private DialogResult ShowImageDetails(ImageDetails imageDetails1)
        {
            Form form1 = new Form();
            form1.ControlBox = false;
            form1.Text = "Add image";
            //form1.MinimumSize = form1.MaximumSize = new System.Drawing.Size(220, 240);
            form1.Size = new System.Drawing.Size(220, 240);
            form1.StartPosition = FormStartPosition.CenterParent;
            imageDetails1.Enabled = true;
            imageDetails1.isEdit = true;
            imageDetails1.Dock = DockStyle.Fill;
            form1.Controls.Add(imageDetails1);
            return  form1.ShowDialog();
        }
        #endregion

        #region | Events |
        public delegate void AddImageToPlaylistHandler(object sender);
        public event AddImageToPlaylistHandler OnImageAdd;
        private void btnAddImage_Click(object sender, EventArgs e)
        {
            ushort imgPO = 0;// play order
            if (((PLAYLIST_POPUP)_popup).Images == null)
                ((PLAYLIST_POPUP)_popup).Images = new List<IMAGE>();

            bool foundID = false;
            for (imgPO = 0; imgPO < ((PLAYLIST_POPUP)_popup).Images.Count; imgPO++)
            {
                foreach (IMAGE p in ((PLAYLIST_POPUP)_popup).Images)
                {
                    if (p.PlayOrder == imgPO)
                    {
                        foundID = true;
                        break;
                    }
                    foundID = false;
                }
                if (foundID)
                    continue;
                break;
            }

            Form form1 = new Form();
            form1.ControlBox = false;
            form1.Text = "Add image";
            //form1.MinimumSize = form1.MaximumSize = new System.Drawing.Size(220, 240);
            form1.Size = new System.Drawing.Size(220, 240);
            form1.StartPosition = FormStartPosition.CenterParent;
            ImageDetails imgDt = new ImageDetails(imgPO);
            imgDt.isEdit = true;
            imgDt.Dock = DockStyle.Fill;
            form1.Controls.Add(imgDt);
            DialogResult dr = form1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                ((PLAYLIST_POPUP)_popup).Images.Add(imgDt.DataSource);
                _popup.ItemCount++;
            }

            populateGallery();
            //TODO: add event here
            if (OnImageAdd != null)
            {
                OnImageAdd(this);
            }
        }

        public delegate void DeleteImageFromPlaylistHandler(object sender, byte playOrder);
        public event DeleteImageFromPlaylistHandler OnImageDelete;
        private void btnDeleteImage_Click(object sender, EventArgs e)
        {
            if (((PLAYLIST_POPUP)_popup).Images.Count <= 1)
                MessageBox.Show("Can't delete this image, playlist must has at least one image!");

            if (selectedImageIndex > 0)
            {
                ((PLAYLIST_POPUP)_popup).Images.RemoveAt(selectedImageIndex);
                populateGallery();
            }
            //btnDeleteImage.Enabled = false;
            // TODO: add delete event here
            //TODO: add event here
            if (OnImageDelete != null)
            {
                OnImageDelete(this, (byte)selectedImageIndex);
            }
        }

        public delegate void UpdateImageHandler(object sender, byte playOrder);
        public event UpdateImageHandler OnImageUpdate;
        private void imgDetailBtnUpdate_Click(object sender, EventArgs e)
        {
            ((PLAYLIST_POPUP)_popup).Images[selectedImageIndex] = imageDetails1.DataSource;
            imageDetails1.Visible = true;
            imageDetails1.Enabled = false;
            if (OnImageUpdate != null)
                OnImageUpdate(this, (byte)selectedImageIndex);
        }
        #endregion

        
    }
}
